// favorites module, added by regret

/* changelog:
 update 2: add Favorites class
 update 1: create
*/

#include "burner.h"
#include "favorites.h"

Favorites::Favorites()
	: favChanged(false)
{
	favoriteMap.clear();
}

Favorites::~Favorites()
{
	favoriteMap.clear();
}

static char* getFavoritesPath()
{
	static char name[MAX_PATH];
	sprintf(name, "config\\favorites.ini");
	return name;
}

bool Favorites::init()
{
	//parse ips dat and update the treewidget
	FILE* file = fopen(getFavoritesPath(), "rt");
	if (!file) {
		return false;
	}

	int i = 0;
	char s[MAX_PATH];
	string line;

	while (!feof(file))
	{
		if (fgets(s, sizeof s, file) != NULL)
		{
			if (s[0] == ';' || (s[0] == '/' && s[1] == '/'))
				continue; // skip comment

			getLineA(s);
			line = s;

			if (line == "[Favorites]" || line == "\r\n" || line == "\n")
				continue;

			favoriteMap[line] = i;
			i++;
		}
	}
	fclose(file);
	return true;
}

bool Favorites::save()
{
	if (!favChanged) {
		return true;
	}

	FILE* file = fopen(getFavoritesPath(), "wt");
	if (!file) {
		return false;
	}

	fprintf(file, "// %ls v%s favorite file\n\n", APP_TITLE, appBurnVer);
	fprintf(file, "[Favorites]\n");

	string game;
	map<string, int>::iterator iter = favoriteMap.begin();
	for(; iter != favoriteMap.end(); iter++)
	{
		game = iter->first;
		if (game != "\r" && game != "\n" && game != "") {
			fprintf(file, "%s\n", game.c_str());
		}
	}
	fclose(file);

	favChanged = false;
	return true;
}

void Favorites::add(unsigned index)
{
	if (index >= BurnGetDrvCount())
		return;

	string game = BurnDrvGetTextA(DRV_NAME, index);

	map<string, int>::iterator iter = favoriteMap.find(game);
	if (iter == favoriteMap.end()) {
		favoriteMap[game] = index;
	}

	favChanged = true;
}

void Favorites::remove(unsigned index)
{
	if (index >= BurnGetDrvCount())
		return;

	string game = BurnDrvGetTextA(DRV_NAME, index);

	map<string, int>::iterator iter = favoriteMap.find(game);
	if (iter != favoriteMap.end()) {
		favoriteMap.erase(iter);
	}

	favChanged = true;
}

bool Favorites::filter(unsigned index)
{
	if (index >= BurnGetDrvCount())
		return false;

	string game = BurnDrvGetTextA(DRV_NAME, index);

	bool ret;
	map<string, int>::iterator iter = favoriteMap.find(game);
	if (iter != favoriteMap.end()) {
		ret = false;
	} else {
		ret = true;
	}

	return ret;
}
